import { defineAsyncComponent } from 'vue';
import { MessagesType } from '@/common/type';
import { RenderComponents } from '../SDK/render.ts';


export class Messages extends RenderComponents {
    static MESSAGE_OBSERVE: any[] = [];
    static MESSAGE_SYMBOL: symbol = Symbol('component');


    constructor() {
        super();
    }

    /**
     * 打开消息提示模板
     * @param options 消息模板参数
     * @param Component 组件对象
     */
    public openMessageTemp(options: MessagesType, Component: any): void {

        const _this = this;

        Messages.MESSAGE_SYMBOL = Symbol('message');

        !options.time && (options.time = 2000);

        // 创建组件实例对象
        let component: any = _this.createComponent(Component, options, null, Messages.MESSAGE_SYMBOL);

        if (Messages.MESSAGE_OBSERVE.length) {
            const message = Messages.MESSAGE_OBSERVE.pop();
            message.clearTimer();
            createMessage(options.time);
        } else {
            createMessage(options.time);
        }

        function createMessage(time?: number){
            const message = {
                id: Messages.MESSAGE_SYMBOL,
                el: component,
                timer: null as any,
                setTimer: function () {
                    this.timer = setTimeout((): void => {
                        Messages.MESSAGE_OBSERVE.pop();
                        _this.unmountComponent(this.el, this.id);
                    }, time);
                    document.body.appendChild(this.el.vnode.el);
                },
                clearTimer: function (): void {
                    _this.unmountComponent(this.el, this.id);
                    clearTimeout(this.timer);
                }
            }
            message.setTimer();
            Messages.MESSAGE_OBSERVE.push(message);
        }
    }
}

const MESSAGE = new Messages();

/**
 * 打开提示信息
 * @param option
 */
const WarmMessage = (option: MessagesType) => MESSAGE.openMessageTemp(option, defineAsyncComponent(() => import('@/components/Warm/Messages/index.vue')));

export {
    WarmMessage
}